/* Copyright 2008. All rights reserved. */
package org.bling.process.events;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.bling.parser.BlingParserException;
import org.bling.process.BlingProcessingException;
import org.bling.process.Request;
import org.bling.process.RequestProcessor;
import org.bling.process.context.ApplicationContext;
import org.bling.process.render.BlingRenderException;
import org.bling.util.Constants;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Listener;

/**
 * <code>EventProcessor</code> acts as a bridge between SWT and the Bling
 * framework.  It is a SWT Listener, which can be attached to SWT widgets
 * (such as buttons) in order to send requests to the request processor
 * when an event occurs (such as clicking a button).
 * 
 * @author DISBROB
 */
public class EventProcessor implements Listener, SelectionListener {

	private static final Logger LOG = LogManager
			.getLogger(EventProcessor.class);

	private String eventActionToPerform = null;

	public EventProcessor(String eventActionToPerform) {
		this.eventActionToPerform = eventActionToPerform;
	}

	/**
	 * @see org.eclipse.swt.widgets.Listener#handleEvent(org.eclipse.swt.widgets.Event)
	 */
	public void handleEvent(Event event) {
		LOG.debug("perform: " + eventActionToPerform);
		LOG.debug("handleEvent - Handle Event");
	}

	/**
	 * @see org.eclipse.swt.events.SelectionListener#widgetDefaultSelected(org.eclipse.swt.events.SelectionEvent)
	 */
	public void widgetDefaultSelected(SelectionEvent e) {
		widgetSelected(e);
	}

	/**
	 * @see org.eclipse.swt.events.SelectionListener#widgetSelected(org.eclipse.swt.events.SelectionEvent)
	 */
	public void widgetSelected(SelectionEvent event) {
		ApplicationContext appContext = ApplicationContext.getInstance();
		RequestProcessor requestProcessor = (RequestProcessor) appContext
				.getAttribute(Constants.ApplicationContextAttributes.REQUEST_PROCESSOR);
		
		try {
			Request request = new Request(eventActionToPerform);
			requestProcessor.process(request);
		} catch (BlingProcessingException e) {
			// FIXME: Add some error handling
			throw new RuntimeException(e.getMessage());
		} catch (BlingParserException e) {
			// FIXME: Add some error handling
			throw new RuntimeException(e.getMessage());
		} catch (BlingRenderException e) {
			// FIXME: Add some error handling
			throw new RuntimeException(e.getMessage());
		}

	}

}
